package servlet;

import domain.Sales;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "/DownloadServlet", value = "/DownloadServlet")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request, response);



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");
//        doGet(request, response);

//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
        String year = request.getParameter("year");
        String month = request.getParameter("month");

        Sales s = new Sales();
        List<Sales> ps = null;
        try {
            ps = s.search(year, month);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String fileName = year+"年"+month+"月销售榜单.csv";
        response.setCharacterEncoding("gb2312");
        response.setContentType("text/html;charset=gb2312");
        response.setContentType(this.getServletContext().getMimeType(fileName));
        response.setHeader("Content-Disposition","attachement;filename="+new String(fileName.getBytes("GBK"),"iso8859-1"));

        PrintWriter out = response.getWriter();
        //out.println(new byte[] {(byte)0xEF,(byte)0xBB,(byte)0xBF});
        out.println("商品名称，销售数量");
        for(int i=0;i<ps.size();i++) {
            Sales arr = ps.get(i);
            out.println(arr.getName()+","+arr.getBuynum());
        }
        out.flush();
        out.close();
    }
}
